import React, {Component} from 'react';
import {Modal, Space, Typography, Descriptions, Button, Divider, message} from "antd"
import {
    apiConsolidatedOrdersDetailPage,
    apiMergeGroupInventoryValidation,
    apiCheckWhetherPushBeing,
    apiPushPhysicalRecords,
    apiUnPushedOrderStatistics
} from "@/request/lotteryTools";
import ThePagination from '@/components/ThePagination';
import TheQueryForm from '@/components/TheQueryForm';
import TheTable from '@/components/TheTable';
import TheButton from '@/components/TheButton';
import '../../component/style.less'
import GoBack from "@/components/TheGoBack";
import {apiGetPhysicalRecordDetails} from "../../../../request/lotteryTools";

const { confirm } = Modal;
const { Paragraph, Text } = Typography;

class Details extends Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [
                {
                    title: "订单号",
                    dataIndex: "orderCode",
                    key: "orderCode",
                },
                {
                    title: "用户ID",
                    dataIndex: "memberId",
                    key: "memberId",
                },
                {
                    title: "用户昵称",
                    dataIndex: "nickName",
                    key: "nickName",
                },
                {
                    title: "收货人",
                    dataIndex: "memberName",
                    key: "memberName",
                },
                {
                    title: "联系方式",
                    dataIndex: "memberPhone",
                    key: "memberPhone",
                },
                {
                    title: "收货地址",
                    dataIndex: "memberAddress",
                    key: "memberAddress",
                },
                {
                    title: "奖品",
                    dataIndex: "prizeName",
                    key: "prizeName",
                },
                {
                    title: "状态",
                    dataIndex: "pushStatus",
                    key: "pushStatus",
                    render: (text, record) => {
                        let label = ""
                        switch (text) {
                            case 0:
                                label = '未推送'
                                break;
                            case 1:
                                label = '已推送'
                                break;
                            default:
                                break;
                        }
                        return label
                    }
                },
                {
                    title: "操作",
                    fixed: "right",
                    // width: 300,
                    render: (text, record) => {
                        return <TheButton onClick={() => this.bookingDetails(record.lotteryDrawPhysicalExchangeRecordsId)}>详情</TheButton>
                    }
                }
            ],
            dataSource: [],
            pageData: {pageNo: 1, pageSize: 10},
            total: 0,
            queryForm: {},
            searchOption: [
                {
                    field: "memberId",
                    label: "用户ID",
                    placeholder: "请输入ID",
                    required: false,
                    rules: [],
                    type: "InputNumber",
                    defaultValue: "",
                },
                {
                    field: 'pushStatus',
                    label: '状态',
                    placeholder: '请选择',
                    required: false,
                    rules: [],
                    type: 'Select',
                    options: [
                        {value: '', label: '全部'},
                        {value: '0', label: '未推送'},
                        {value: '1',label: '已推送'}
                    ],
                    defaultValue: ''
                },
            ],
            selectedRowKeys: [],
            isModalOpen: false,
            mergeGroupsId: null,
            detailsData: {},
            outOfStockCount: 0,
            unPushedOrderCount: 0
        }
    }

    componentDidMount() {
        this.setState({
            mergeGroupsId: this.props.match.params.id
        },()=>{
            this.getData()
            this.getUnPushedOrderStatistics()
        })
    }
    getUnPushedOrderStatistics = async () => {
        let {mergeGroupsId} = this.state;
        let res = await apiUnPushedOrderStatistics({
            mergeGroupsId
        })
        if (res.code === 0){
            this.setState({
                outOfStockCount: res.data.outOfStockCount,
                unPushedOrderCount: res.data.unPushedOrderCount
            })
        }
    }
    getPushStatus = async () => {
        let {mergeGroupsId} = this.state;
        let res = await apiCheckWhetherPushBeing({
            mergeGroupsId
        })
        if (res.code === 0) {
            return res.data
        }
    }

    getData = () => {
        let {pageNo, pageSize} = this.state.pageData;
        let {queryForm,mergeGroupsId} = this.state;
        apiConsolidatedOrdersDetailPage({
            pageNo,
            pageSize,
            mergeGroupsId,
            ...queryForm
        }).then(res => {
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })

    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => this.getData())
    }

    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }

    onFormSearch(values) {
        this.setState({
            queryForm: values,
            pageData: {pageNo: 1, pageSize: this.state.pageData.pageSize}
        }, () => {
            this.getData()
        })
    }

    onSelectChange = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
        })
    }
    // 一键
    oneKeyMerge = async () => {
        let pushStatus = await this.getPushStatus();
        if (pushStatus){
            return message.error('有订单正在推送中，请稍后重试。')
        }else {
            let {selectedRowKeys,mergeGroupsId} = this.state;
            let data = await this.getInventoryDetails(selectedRowKeys);
            confirm({
                title: <p style={{textAlign: 'center'}}>温馨提示</p>,
                icon: null,
                width: 600,
                content: <div>
                    {data}
                    <Divider />
                    继续执行将按照顺序进行订单推送，部分订单因库存不足，不予推送！
                    <Divider />
                </div>,
                onOk: async () => {
                    let res = await apiPushPhysicalRecords({
                        mergeGroupsId,
                        physicalExchangeRecordsIds: selectedRowKeys
                    })
                    if (res.code === 0){
                        message.success('推送成功')
                        this.setState({
                            selectedRowKeys: []
                        })
                        this.getData()
                        this.getUnPushedOrderStatistics()
                    }
                },
                okText: '继续执行'
            });
        }

    }
    getInventoryDetails = async (physicalExchangeRecordsIds) => {
        let {mergeGroupsId,selectedRowKeys} = this.state;
        let res = await apiMergeGroupInventoryValidation({
            mergeGroupsId,
            physicalExchangeRecordsIds
        })
        if (res.code === 0){
            let arr = []
            if (res.data && res.data.length > 0){
                res.data.forEach((item,index)=>{
                    arr.push(<Space wrap key={index} className={'prize-space'}>
                        <span>奖品：</span>
                        <span className={'prize-name-wrap'}>{item.prizeName}</span>
                        <span>需要数量</span>
                        <span style={{color: 'red'}}>{item.prizeCount}</span>
                        <span>件，当前库存</span>
                        <span style={{color: 'red'}}>{item.inventoryCount}</span>
                        <span>件</span>
                    </Space>)
                })
            }
            return arr
        }
    }
    // 库存详情
    inventoryDetails = async () => {
        let data = await this.getInventoryDetails([]);
        let modal = Modal.confirm();
        modal.update({
            title: <p style={{textAlign: 'center'}}>库存详情</p>,
            icon: null,
            width: 600,
            content: data,
            onOk: (e) => {
                this.getUnPushedOrderStatistics()
                this.getInventoryDetails([]).then(res=>{
                    modal.update({
                        content: res,
                    })
                });
            },
            cancelText: '确定',
            okText: '校验库存'
        });
    }
    // 预订单详情
    bookingDetails = (id) => {
        apiGetPhysicalRecordDetails({
            lotteryDrawPhysicalExchangeRecordsId: id
        }).then(res=>{
            if (res.code === 0){
                this.setState({
                    isModalOpen:true,
                    detailsData: res.data
                })
            }
        })
    }
    render() {
        const {columns, dataSource, pageData: {pageNo, pageSize}, total, searchOption, selectedRowKeys, isModalOpen, detailsData, outOfStockCount, unPushedOrderCount } = this.state;
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys,
            preserveSelectedRowKeys: true,
            onChange: this.onSelectChange,
            getCheckboxProps: (record) => {
                return {
                    disabled: record.pushStatus
                }
            },
        };
        return <div className='p-layout-box'>
            <GoBack history={this.props.history} title={"订单详情"}/><br/>
            <TheQueryForm
                ref={(ref) => (this.queryFormRef = ref)}
                show={true}
                option={searchOption}
                onReset={() => this.onReset()}
                onGetValues={(values) => this.onFormSearch(values)}
            >
                <TheButton
                    haspermi={['winningRecord:mergeRecord:details:oneKeyPush']}
                    type="default"
                    size="middle"
                    onClick={() => this.oneKeyMerge()}
                >
                    一键推送
                </TheButton>
            </TheQueryForm>
            <Space size={40}>
                <span>未推送订单奖品数量: {unPushedOrderCount}</span>
                <span>缺货数量:<span style={{color: 'red'}}>{outOfStockCount}</span></span>
                <TheButton onClick={() => this.inventoryDetails()}>详情</TheButton>
            </Space>
            <br/>
            <TheTable
                rowKey={"lotteryDrawPhysicalExchangeRecordsId"}
                scroll={{x: 'max-content', y: '63vh'}}
                columns={columns}
                dataSource={dataSource}
                rowSelection={rowSelection}
            />
            <ThePagination
                pageNo={pageNo}
                pageSize={pageSize}
                total={total}
                showQuickJumper={true}
                pageSizeOptions={[10, 50, 100, 300, 500]}
                pageChange={this.pageChange}
            />
            <Modal
                title="预订单详情"
                open={isModalOpen}
                onCancel={()=>this.setState({isModalOpen:false})}
                footer={[
                    <Button key="back" onClick={()=>this.setState({isModalOpen: false})}>
                        确定
                    </Button>
                ]}
            >
                <Descriptions
                    title=""
                    layout="vertical"
                    // bordered
                    labelStyle={{
                        fontWeight: 700,
                    }}
                    column={2}
                >
                    <Descriptions.Item label="用户ID">{detailsData.memberId}</Descriptions.Item>
                    <Descriptions.Item label="用户昵称">{detailsData.nickName}</Descriptions.Item>
                    <Descriptions.Item label="收货人">{detailsData.memberName}</Descriptions.Item>
                    <Descriptions.Item label="联系方式">{detailsData.memberPhone}</Descriptions.Item>
                    <Descriptions.Item label="收获地址" span={2}>
                        {detailsData.memberAddress}
                    </Descriptions.Item>
                    <Descriptions.Item label="奖品" span={2}>
                        {detailsData.prizeName}
                    </Descriptions.Item>
                </Descriptions>
            </Modal>
        </div>;
    }
}

export default Details;
